using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Windows.Forms;
using System.Globalization;
using System.Net;
using System.Net.NetworkInformation;

namespace THSLib
{
    public class THSUtil
    {
        #region --Variable--
        public static long countInvoke = 0;
        public const String cstDummyTable = "CSDummy";
        #endregion            
        #region --Display--
            
            public static String NewLine
            {
                get
                {
                    return "\n";
                }
            }

            public static String Tab
            {
                get
                {
                    return "\t";
                }
            }

            /// <summary>
            /// Get number display format
            /// </summary>
            /// 
            public static String GetNumberDisplayFormat(object number)
            {
                if (number.GetType() == typeof(double))
                    number = Math.Round(Convert.ToDouble(number), NumberFormatInfo.CurrentInfo.NumberDecimalDigits);
                else if (number.GetType() == typeof(decimal))
                    number = Math.Round(Convert.ToDecimal(number), NumberFormatInfo.CurrentInfo.NumberDecimalDigits);

                String str = number.ToString();
                String sign = String.Empty;
                if ((str.Length > 0) && str[0] == '-')
                {
                    sign = "-";
                    str = str.Remove(0, 1);
                }

                String left = String.Empty;
                String right = String.Empty;
                String[] arr = str.Split(new string[] { NumberFormatInfo.CurrentInfo.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);
                if (arr.Length > 0)
                    left = arr[0];
                if (arr.Length > 1)
                    right = arr[1];
                str = String.Empty;
                for (int i = 0; i < left.Length; i++)
                {
                    if ((i + 1) % 3 == 0 && i < left.Length - 1)
                        str = NumberFormatInfo.CurrentInfo.NumberGroupSeparator + left[left.Length - i - 1] + str;
                    else
                        str = left[left.Length - i - 1] + str;
                }

                if (number.GetType() == typeof(double) || number.GetType() == typeof(decimal))
                {
                    while (right.Length < NumberFormatInfo.CurrentInfo.NumberDecimalDigits)
                        right += "0";
                    str = String.Format("{0}{1}{2}{3}", sign, str, NumberFormatInfo.CurrentInfo.NumberDecimalSeparator, right);
                }
                else if (number.GetType() == typeof(int))
                    str = String.Format("{0}{1}", sign, str);
                return str;
            }

            public static String GetTableNameAlias(String strTblName)
            {
                AATableNameAliasController objAATableNameAliasController = new AATableNameAliasController();
                AATableNameAliasInfo objAATableNameAliasInfo = (AATableNameAliasInfo)objAATableNameAliasController.GetAATableNameAliasByTableName(strTblName);

                //if exists
                if (objAATableNameAliasInfo != null)
                {
                    return objAATableNameAliasInfo.AATableNameAliasCaption;
                }

                return String.Empty;

            }

            public static String GetColumnAlias(String strColName, String strTblName)
            {
                AAColumnAliasController objAAColumnAliasController = new AAColumnAliasController();
                AAColumnAliasInfo objAAColumnAliasInfo = (AAColumnAliasInfo)objAAColumnAliasController.GetAAColumnAliasByColumnNameAndTableName(strColName, strTblName);

                //if exists
                if (objAAColumnAliasInfo != null)
                {
                    return objAAColumnAliasInfo.AAColumnAliasCaption;
                }

                return String.Empty;

            }
        public static double Round(double dbNumber, int iDigit)
        {
            return Math.Round(dbNumber, iDigit, MidpointRounding.AwayFromZero);
        }
	
        #endregion
        #region --Type--

            public static String GetFullTypeName(String strTypeName)
            {

                String strFullTypeName = strTypeName;
                switch (strTypeName)
                {
                    case "Int32":
                        {
                            strFullTypeName = "System." + strTypeName;
                            break;
                        }
                }
                return strFullTypeName;
            }

            public static Type GetTHSType(String strFullTypeName, String strAssembly)
            {
                try
                {
                    Assembly THSAssembly = Assembly.Load(strAssembly);
                    if (THSAssembly != null)
                    {
                        return THSAssembly.GetType(strFullTypeName);
                    }
                    else
                        return null;
                }
                catch (Exception)
                {
                    return null;
                }
            }

            public static String GetTableNameFromBusinessObject(BusinessObject objInfo)
            {
                if (objInfo != null)
                {
                    String strBusinessObjectName = objInfo.GetType().Name;
                    String strTableName = strBusinessObjectName.Substring(0, strBusinessObjectName.Length - 4);
                    return strTableName;
                }
                else
                    return cstDummyTable;
            }

            public static String GetTableNameFromBusinessObjectType(Type tpBusinessObject)
            {
                String strBusinessObjectName = tpBusinessObject.Name;
                String strTableName = strBusinessObjectName.Substring(0, strBusinessObjectName.Length - 4);
                return strTableName;
            }

            public static String GetBusinessControllerNameFromBusinessObject(BusinessObject objInfo)
            {
                String strTableName = GetTableNameFromBusinessObject(objInfo);
                return strTableName + "Controller";
            }

            public static String GetModuleName(String strTableName)
            {
                String strModuleName = strTableName.Substring(2, strTableName.Length - 3);
                if (strModuleName.EndsWith("ie"))
                    strModuleName = strModuleName.Substring(0, strModuleName.Length - 2) + "y";

                return strModuleName;
            }

            public static String GetCSharpVariableType(String strTableName, String strColumnName)
            {

                String strColumnDataType = THSDbUtil.GetColumnDataType(strTableName, strColumnName);
                switch (strColumnDataType)
                {
                    case "varchar":
                        return "String";
                    case "nvarchar":
                        return "String";
                    case "text":
                        return "String";
                    case "ntext":
                        return "String";
                    case "nchar":
                        return "String";
                    case "int":
                        return "int";
                    case "float":
                        return "double";
                    case "real":
                        return "double";
                    case "decimal":
                        return "decimal";
                    case "datetime":
                        return "DateTime";
                    case "bit":
                        return "bool";
                    case "image":
                        return "byte[]";
                    case "varbinary":
                        return "byte[]";
                    default:
                        return "_UNKNOWN_";
                }
            }

            public static Type GetColumnDataType(String strTableName, String strColumnName)
            {

                String strColumnDataType = THSDbUtil.GetColumnDataType(strTableName, strColumnName);
                switch (strColumnDataType)
                {
                    case "varchar":
                        return typeof(String);
                    case "nvarchar":
                        return typeof(String);
                    case "text":
                        return typeof(String);
                    case "ntext":
                        return typeof(String);
                    case "int":
                        return typeof(int);
                    case "float":
                        return typeof(double);
                    case "real":
                        return typeof(double);
                    case "decimal":
                        return typeof(decimal);
                    case "datetime":
                        return typeof(DateTime);
                    case "bit":
                        return typeof(bool);
                    case "image":
                        return typeof(byte[]);
                    case "varbinary":
                        return typeof(byte[]);
                    default:
                        return typeof(String);

                }
            }

            public static DevExpress.Utils.FormatType GetFormatTypeFromText(String strFormatType)
            {
                try
                {
                    return (DevExpress.Utils.FormatType)Enum.Parse(typeof(DevExpress.Utils.FormatType), strFormatType);
                }
                catch (Exception)
                {
                    return DevExpress.Utils.FormatType.None;
                }
            }
        #endregion
        #region --Datetime--

        public static DateTime GetYearBeginDate()
        {
            return new DateTime(DateTime.Now.Year, 1, 1);
        }

        public static DateTime GetYearEndDate()
        {
            return new DateTime(DateTime.Now.Year, 12, 31);
        }
        #endregion        
        public static bool ObjectIsEditingByOtherUser(String strModuleName, int iObjectID)
        {
            if (iObjectID > 0)
            {
                GEUserAuditsController objGEUserAuditsController = new GEUserAuditsController();
                GEUserAuditsInfo objGEUserAuditsInfo = objGEUserAuditsController.GetGEUserAuditsByModuleNameAndParameterAndAction(
                                                                                    strModuleName,
                                                                                    iObjectID.ToString(),
                                                                                    BaseToolbar.ModusEdit);
                if (objGEUserAuditsInfo != null)
                {                    
                    return true;
                }
            }

            return false;
        }

      
        #region --Copy,Duplicate--
        public static void CopyMainObjects(BusinessObject objFromObjectsInfo, BusinessObject objToObjectsInfo)
        {
            
            String strToObjectTableName = THSUtil.GetTableNameFromBusinessObject(objToObjectsInfo);
            String strFromObjectTableName = THSUtil.GetTableNameFromBusinessObject(objFromObjectsInfo);

            PropertyInfo[] properties = objToObjectsInfo.GetType().GetProperties();
            foreach (PropertyInfo prop in properties)
            {
                if (!THSDbUtil.IsPrimaryKey(strToObjectTableName, prop.Name))
                {
                    if (!THSDbUtil.IsForeignKey(strToObjectTableName, prop.Name))
                    {
                        if (prop.Name.StartsWith(strToObjectTableName.Substring(0, strToObjectTableName.Length - 1)))
                        {
                            String strFromObjectPropertyName = strFromObjectTableName.Substring(0, strFromObjectTableName.Length - 1) + prop.Name.Substring(strToObjectTableName.Length - 1);
                            PropertyInfo propFromObjectProperty = objFromObjectsInfo.GetType().GetProperty(strFromObjectPropertyName);
                            if (propFromObjectProperty != null)
                            {
                                object objValue = propFromObjectProperty.GetValue(objFromObjectsInfo, null);
                                prop.SetValue(objToObjectsInfo, objValue, null);
                            }
                        }
                        else
                        {
                            PropertyInfo propFromObjectPropertyerty = objFromObjectsInfo.GetType().GetProperty(strFromObjectTableName.Substring(0, 2) + prop.Name.Substring(2));
                            if (propFromObjectPropertyerty != null)
                            {
                                object objValue = propFromObjectPropertyerty.GetValue(objFromObjectsInfo, null);
                                prop.SetValue(objToObjectsInfo, objValue, null);
                            }
                        }
                    }
                    else
                    {
                        PropertyInfo propFromObjectProperty = objFromObjectsInfo.GetType().GetProperty(prop.Name);
                        if (propFromObjectProperty != null)
                        {
                            object objValue = propFromObjectProperty.GetValue(objFromObjectsInfo, null);
                            prop.SetValue(objToObjectsInfo, objValue, null);
                        }
                    }
                }

            }
        }

        public static void CopyObjectItems(BusinessObject objFromObjectItems, BusinessObject objToObjectItems,String strToObjectTableName)
        {
            
            String strFromObjectItemsTableName = GetTableNameFromBusinessObject(objFromObjectItems);
            String strToObjectItemsTableName = GetTableNameFromBusinessObject(objToObjectItems);
            String strToObjectTablePrimaryKey = THSDbUtil.GetTablePrimaryColumn(strToObjectTableName);

            PropertyInfo[] properties = objToObjectItems.GetType().GetProperties();
            foreach (PropertyInfo prop in properties)
            {
                if (!THSDbUtil.IsPrimaryKey(strToObjectItemsTableName, prop.Name))
                {
                    if (!THSDbUtil.IsForeignKey(strToObjectItemsTableName, prop.Name))
                    {
                        if (prop.Name.StartsWith(strToObjectItemsTableName.Substring(0, strToObjectItemsTableName.Length - 1)))
                        {
                            String strFromModuleItemPropertyName = strFromObjectItemsTableName.Substring(0, strFromObjectItemsTableName.Length - 1) + prop.Name.Substring(strToObjectItemsTableName.Length - 1);
                            PropertyInfo propFromModuleItemProperty = objFromObjectItems.GetType().GetProperty(strFromModuleItemPropertyName);
                            if (propFromModuleItemProperty != null)
                            {
                                object objValue = THSLib.DynamicInvoker.DynamicGetValue( objFromObjectItems , propFromModuleItemProperty );
                                THSLib.DynamicInvoker.DynamicSetValue( objToObjectItems , prop , objValue );
                            }
                        }
                    }
                    else
                    {
                        
                        if (!prop.Name.Equals("FK_"+strToObjectTablePrimaryKey))
                        {
                            PropertyInfo propFromModuleItemProperty = objFromObjectItems.GetType().GetProperty(prop.Name);
                            if (propFromModuleItemProperty != null)
                            {
                                object objValue = THSLib.DynamicInvoker.DynamicGetValue( objFromObjectItems , propFromModuleItemProperty );
                                THSLib.DynamicInvoker.DynamicSetValue( objToObjectItems , prop , objValue );
                            }
                        }
                    }
                }
            }
        }

        public static void CopyObject(BusinessObject objFromObject, BusinessObject objToObject)
        {
            String strFromObjectTableName = GetTableNameFromBusinessObject(objFromObject);
            String strToObjectTableName = GetTableNameFromBusinessObject(objToObject);            

            PropertyInfo[] properties = objToObject.GetType().GetProperties();
            foreach (PropertyInfo prop in properties)
            {
                if (!THSDbUtil.IsPrimaryKey(strToObjectTableName, prop.Name))
                {
                    if (!THSDbUtil.IsForeignKey(strToObjectTableName, prop.Name))
                    {
                        if (prop.Name.StartsWith(strToObjectTableName.Substring(0, strToObjectTableName.Length - 1)))
                        {
                            String strFromModuleItemPropertyName = strFromObjectTableName.Substring(0, strFromObjectTableName.Length - 1) + prop.Name.Substring(strToObjectTableName.Length - 1);
                            if (strFromModuleItemPropertyName != strFromObjectTableName.Substring(0, strFromObjectTableName.Length - 1) + "No")
                            {
                                PropertyInfo propFromModuleItemProperty = objFromObject.GetType().GetProperty(strFromModuleItemPropertyName);
                                if (propFromModuleItemProperty != null)
                                {
                                    object objValue = THSLib.DynamicInvoker.DynamicGetValue( objFromObject , propFromModuleItemProperty );
                                    THSLib.DynamicInvoker.DynamicSetValue( objToObject , prop , objValue );
                                }
                            }
                        }
                    }
                    else
                    {                        
                        PropertyInfo propFromModuleItemProperty = objFromObject.GetType().GetProperty(prop.Name);
                        if (propFromModuleItemProperty != null)
                        {
                            object objValue = THSLib.DynamicInvoker.DynamicGetValue( objFromObject , propFromModuleItemProperty );
                            THSLib.DynamicInvoker.DynamicSetValue( objToObject , prop , objValue );
                        }
                        
                    }
                }
            }
        }
       
        #endregion
        public static DevExpress.XtraEditors.Mask.MaskType GetMaskTypeFromText(String strMaskType)
        {
            try
            {
                return (DevExpress.XtraEditors.Mask.MaskType)Enum.Parse(typeof(DevExpress.XtraEditors.Mask.MaskType), strMaskType);
            }
            catch (Exception)
            {
                return DevExpress.XtraEditors.Mask.MaskType.None;
            }
        }

        public static DevExpress.XtraEditors.Repository.RepositoryItem GetRepositoryItemFromText(String strRepositoryItem)
        {
            switch (strRepositoryItem)
            {
                case "RepositoryItemTextEdit":
                    return new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();
                case "RepositoryItemHyperLinkEdit":
                    return new DevExpress.XtraEditors.Repository.RepositoryItemHyperLinkEdit();
                case "RepositoryItemComboBox":
                    return new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
                case "RepositoryItemDateEdit":
                    return new DevExpress.XtraEditors.Repository.RepositoryItemDateEdit();
                case "RepositoryItemTimeEdit":
                    return new DevExpress.XtraEditors.Repository.RepositoryItemTimeEdit();
                case "RepositoryItemLookupEdit":
                    return new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();        
                default:
                    return null;
            }
        }

        public static bool IsEditControl(Control ctrl)
        {
            if (ctrl.GetType().Name.Contains("Edit"))
                return true;
            return false;
        }

        public static bool IsEditRepository(DevExpress.XtraEditors.Repository.RepositoryItem rep)
        {
            if (rep.GetType() == typeof(DevExpress.XtraEditors.Repository.RepositoryItemTextEdit))
                return true;
            if (rep.GetType() == typeof(DevExpress.XtraEditors.Repository.RepositoryItemComboBox))
                return true;
            if (rep.GetType() == typeof(DevExpress.XtraEditors.Repository.RepositoryItemDateEdit))
                return true;
            if (rep.GetType() == typeof(DevExpress.XtraEditors.Repository.RepositoryItemTimeEdit))
                return true;
            if (rep.GetType() == typeof(DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit))
                return true;
            return false;
        }

        /// <summary>
        /// Reverse string
        /// </summary>
        /// 
        public static String ReverseString(String str)
        {
            String result = String.Empty;
            for (int i = str.Length - 1; i >= 0; i--)
                result += str[i];
            return result;
        }

        #region --Physics-
        public static bool IsValidPath(String path)
        {
            try
            {
                Char[] cArray = path.ToCharArray();
                for (int i = 0; i < cArray.Length; i++)
                {
                    if (cArray[i].ToString().Equals("\\"))
                    {
                        String strCheck = cArray.GetValue(i + 1).ToString();
                        if (strCheck.Equals("\\"))
                            return false;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return true;
        }
        public static bool IsFileNull(String path)
        {
            try
            {
                FileInfo file = new FileInfo(path);
                String strFileName = file.Name;
                if (strFileName != "")
                {
                    if (strFileName.EndsWith(".xlsx"))
                        return true;
                    else if (strFileName.EndsWith(".xls"))
                        return true;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("catch IsFileNull function " + ex.Message);
            }
            return false;
        }

        public static bool IsDrive(String val)
        {
            String[] strDriveName = val.Split('\\');
            string[] drives = Directory.GetLogicalDrives();
            foreach (string drive in drives)
            {
                foreach (String strDrive in strDriveName)
                {
                    if (drive.Equals(strDrive.ToUpper() + "\\")) return true;
                }
            }
            return false;
        }
        public static bool IsDirectory(String path)
        {
            try
            {
                FileInfo file = new FileInfo(path);
                String strFileName = file.Name;
                if (strFileName != "")
                {
                    String strDir = path.Replace(strFileName, "");
                    if (Directory.Exists(strDir))
                        return true;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("catch IsDirectory function "+ ex.Message);
            }
            return false;
        }
        public static List<String> GetLocalIPAddress()
        {
            List<String> lstHost = new List<String>();
            String strHostName = String.Empty;
            String strHostIPAddress = String.Empty;

            //To Get the local IP address
            strHostName = Dns.GetHostName();
            lstHost.Add(strHostName);
            IPHostEntry objIPHostEntry = Dns.GetHostByName(strHostName);
            IPAddress[] objIPAddressList = objIPHostEntry.AddressList;
            foreach (IPAddress ip in objIPAddressList)
            {
                strHostIPAddress = ip.ToString();
                lstHost.Add(strHostIPAddress);
            }
            return lstHost;
        }
        #endregion

     	
    }
}
